//
//  StatusViewModel.swift
//  SinaBlog
//
//  Created by macs on 15/11/16.
//  Copyright © 2015年 BlackTail. All rights reserved.
//

import UIKit
import SDWebImage

class StatusViewModel: NSObject {
    
    
    func getStatues(since_id since_id : Int, max_id : Int ,finished : (array : [Status]?) ->()){
        let urlString = "2/statuses/home_timeline.json"
        guard let token = AccessViewModel().access_token else {
            return
        }
        var parameters = ["access_token" : token] as [String : AnyObject]
        //since_id 若指定此参数，则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0。
        if since_id != 0 {
            
            parameters["since_id"] = since_id
            
        }
        //若指定此参数，则返回ID小于或等于max_id的微博，默认为0。
        if max_id != 0 {
            parameters["max_id"] = max_id - 1
        }
        
        Networktools.shareTools.requestJsonDict(HTTPType.GET, urlSting: urlString, parameters: parameters) { (result, error) -> () in
            
            if error != nil {
                finished(array: nil)
                return
            }
            if let array = result!["statuses"] as? [[String : AnyObject]]{
                var list = [Status]()
                for dictionary in array {
                    //字典转模型
                    //print(dictionary)
                    let sta = Status(dict: dictionary )
                    
                    list.append(sta)
                }
                self.cacheStatusImage(list, finished: finished)
                
            }
        }
    }
    
    private func cacheStatusImage (array : [Status] , finished : (array : [Status]?) ->()  ) {
        
        if array.count == 0 {
            finished(array: nil)
            return
        }
        
        //开启线程组
        let imageGroup = dispatch_group_create()
        //遍历模型对象
        for sta in array {
            //获取图片地址数组
            if let imagepurls = sta.danzhangPicUrl {
                //不是单张图片,寻找下一个
                if imagepurls.count != 1 {
                    continue
                }
            
                //加载单张图片
                for ima in imagepurls {
                    //异步加载图片,往线程组中添加任务
                    dispatch_group_enter(imageGroup)
                    SDWebImageManager.sharedManager().downloadImageWithURL(ima, options: [], progress:nil, completed: { (_ , _ , _, _, _) -> Void in
                        
                        //print("单张图片加载完毕")
                        //异步任务离开线程组
                        dispatch_group_leave(imageGroup)
                    })
                }
            }
        }
        //在主线程中进行线程回调
        
        dispatch_group_notify(imageGroup, dispatch_get_main_queue()) { () -> Void in
           // print("所有单张图片加载完成")
            finished(array: array)
        }
        
    }
    
}
